<?php
/**
 * Created by PhpStorm.
 * User: Xwen
 * Date: 2018/12/19
 * Time: 22:14
 *
 *          ┌─┐       ┌─┐
 *       ┌──┘ ┴───────┘ ┴──┐
 *       │                 │
 *       │       ───       │
 *       │  ─┬┘       └┬─  │
 *       │                 │
 *       │       ─┴─       │
 *       │                 │
 *       └───┐         ┌───┘
 *           │         │
 *           │         │
 *           │         │
 *           │         └──────────────┐
 *           │                        │
 *           │                        ├─┐
 *           │                        ┌─┘
 *           │                        │
 *           └─┐  ┐  ┌───────┬──┐  ┌──┘
 *             │ ─┤ ─┤       │ ─┤ ─┤
 *             └──┴──┘       └──┴──┘
 *                 神兽保佑
 *                 代码无BUG!
 *"The trouble with programmers is that you can never tell what a programmer is doing until it’s too late.”- Seymour Cray
 */

namespace app\admin\logic;

use app\admin\Validate\Menu as MenuValidate;
use think\Db;
use think\Session;

class Menu
{
    public function infos($pageNumber, $pageSize, $name = NULL){
        $where[] = ['is_delete', '=', 0];
        $where1[] = ['is_delete', '=', 0];
        if($name != NULL){
            $where[] = ['menu_name', 'LIKE', '%'.$name.'%'];
        }
        $data = model("Menu")->getPage($where, $pageNumber, $pageSize);
        $count = model("Menu")->getCount($where);
        foreach ($data as $k => $v) {
            if ($v['pid'] == 0) {
                $data[$k]['pid_title'] = '一级菜单';
            }else {
                $where1[] = ['id', 'eq', $v['pid']];
                $res = model("Menu")->where($where1)->field('menu_name')->find();
                $data[$k]['pid_title'] = $res['menu_name'];
                array_pop($where1);
            }
        }
        return [
            'total'      =>         $count,
            'rows'       =>         $data,
        ];
    }
    public function add($data){
        $validate = new MenuValidate;
        if ($data['pid'] == 0) {
            $result = $validate->scene('addOne')->check($data);
        }else{
            $result = $validate->scene('addTwo')->check($data);
        }
        if (!$result) {
            exception($validate->getError());
        }
        $pData['permission_name'] = $data['menu_name'];
        $pData['permission_type'] = 1;

        $adminName = (new Session())->get('USER_INFO.userName');
        $info['creator'] = $adminName;
        $info['updater'] = $adminName;
        $info['create_time'] = time();
        $info['update_time'] = time();
        $data = array_merge($data, $info);
        $pData = array_merge($pData, $info);
        Db::startTrans();
        try{
            $menu = model("Menu")->insertGetId($data);
            $permission = model('Permission')->insertGetId($pData);
            $prData['permission_id'] = $permission;
            $prData['menu_id'] = $menu;
            $prData = array_merge($prData, $info);
            model('PermissionMenu')->insert($prData);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
        return true;
    }

    public function getParent(){
//        $where0[] = ['is_delete', '=', 0];
//        $where0[] = ['pid', 'eq', 0];
//        $where1[] = ['is_delete', '=', 0];
//        $data = model('Menu')->getBy($where0)->toarray();
//        foreach ($data as $k => $v) {
//            $where1[] = ['pid', 'eq', $v['id']];
//            $second = model('Menu')->getBy($where1)->toarray();
//            $data = array_merge($data, $second);
//            array_pop($where1);
//        }
//        return $data;
        $where0[] = ['is_delete', '=', 0];
        $where0[] = ['pid', 'eq', 0];
        $where1[] = ['is_delete', '=', 0];
        $data = model('Menu')->getBy($where0);
        foreach ($data as $k => $v) {
            $where1[] = ['pid', 'eq', $v['id']];
            $second = model('Menu')->getBy($where1);
            $data[$k]['second'] = $second;
            array_pop($where1);
        }
        return $data;
    }
    public function getAll(){
        $where0[] = ['is_delete', '=', 0];
        $where0[] = ['pid', 'eq', 0];
        $where1[] = ['is_delete', '=', 0];
        $where2[] = ['is_delete', '=', 0];
        $data = model('Menu')->getBy($where0);
        foreach ($data as $k => $v) {
            $where1[] = ['pid', 'eq', $v['id']];
            $second = model('Menu')->getBy($where1);
            foreach ($second as $ks => $vs) {
                $where2[] = ['pid', 'eq', $vs['id']];
                $third = model('Menu')->getBy($where2);
                $second[$ks]['third'] = $third;
                array_pop($where2);
            }
            $data[$k]['second'] = $second;
            array_pop($where1);
        }
        return $data;
    }



    public function getAllWithPermission(){
        $where0[] = ['is_delete', '=', 0];
        $where0[] = ['pid', 'eq', 0];
        $where1[] = ['is_delete', '=', 0];
        $data = model('Menu')->getBy($where0);
        foreach ($data as $k => $v) {
            $where1[] = ['pid', 'eq', $v['id']];
            $second = model('Menu')->getBy($where1);
            $data[$k]['second'] = $second;
            array_pop($where1);
        }
        return $data;
    }
    public function edit($data){
        $validate = new MenuValidate;
        if ($data['pid'] == 0) {
            $result = $validate->scene('editOne')->check($data);
        }else{
            $result = $validate->scene('editTwo')->check($data);
        }
        if (!$result) {
            exception($validate->getError());
        }
        $adminName = (new Session())->get('USER_INFO.userName');
        $info['updater'] = $adminName;
        $info['update_time'] = time();
        $data = array_merge($data, $info);

        $id = $data['id'];
        unset($data['id']);

        $prWhere[] = ['is_delete', '=', 0];
        $prWhere[] = ['menu_id', '=', $id];

        Db::startTrans();
        try{
            $info['creator'] = $adminName;
            $info['create_time'] = time();
            model("Menu")->save($data, ['id' => $id]);
            $pr = model('PermissionMenu')->where($prWhere)->field('permission_id')->find();

            $pWhere[] = ['is_delete', '=', 0];
            $pWhere[] = ['id', 'eq', $pr['permission_id']];
            $pWhere[] = ['permission_type', 'eq', 1];
            $pData['permission_name'] = $data['menu_name'];
            $pData = array_merge($pData, $info);
            model('Permission')->where($pWhere)->update($pData);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
        return true;
    }
    public function delete($id){
        $validate = new MenuValidate;
        $result = $validate->scene('delete')->check($id);
        if (!$result) {
            exception($validate->getError());
        }
        $adminName = (new Session())->get('USER_INFO.userName');
        $data = [];
        $data['updater'] = $adminName;
        $data['update_time'] = time();
        $data['is_delete'] = 1;
        Db::startTrans();
        try{
            model("Menu")->save($data, ['id' => $id]);
            $pmWhere[] = ['is_delete', '=', 0];
            $pmWhere[] = ['menu_id', 'eq', $id['id']];
            $permission = model('PermissionMenu')->where($pmWhere)->field('permission_id')->find();
            if ($permission) {
                model('PermissionMenu')->where($pmWhere)->update($data);
                $pWhere[] = ['is_delete', '=', 0];
                $pWhere[] = ['id', 'eq', $permission['permission_id']];
                model('Permission')->where($pWhere)->update($data);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
        return true;
    }

}